#include "rpc_message_codec.h"

#include "xlcomm/net/buffer.h"
#include "xlcomm/net/tcp_connection.h"

namespace xlcomm {
namespace net {

void RpcMessageCodec::OnMessage(const net::TcpConnectionPtr& conn,
                                net::Buffer* buff, Timestamp recv_time) {
  LOG_DEBUG << "RpcMessageCodec::OnMessage==== in";
  while (buff->ReadableBytes() >= kHeaderSize) {
    int len = buff->PeekInt32ToHost();
    LOG_DEBUG << "RpcMessageCodec::OnMessage==== buff->ReadableBytes():"
              << buff->ReadableBytes() << " msgLen:" << len;
    if (static_cast<int>(buff->ReadableBytes()) < kHeaderSize + len) break;

    RpcMessage rpcmsg;
    LOG_DEBUG << "RpcMessageCodec::ParseRpcMessage====";
    buff->ReadInt32ToHost();
    std::string msgstr = buff->ReadString(len);
    rpcmsg.ParseFromString(msgstr);

    if (rpc_message_cb_) rpc_message_cb_(conn, rpcmsg);
  }
}

void RpcMessageCodec::SendRpcMessage(const net::TcpConnectionPtr& conn,
                                     const RpcMessage& rpcmsg) {
  LOG_DEBUG << "RpcMessageCodec::SendRpcMessage==== in";
  std::string ret_str;
  rpcmsg.SerializeToString(&ret_str);

  // size(4Byte)+rpcmsg
  net::Buffer buffer;
  buffer.Append(ret_str);
  buffer.PrependInt32ToNet(static_cast<int>(ret_str.length()));
  LOG_DEBUG << "RpcMessageCodec::SendRpcMessage==== buffer.ReadableBytes():"
            << buffer.ReadableBytes() << " msgLen:" << ret_str.length();
  conn->Send(&buffer);
}

}  // namespace net
}  // namespace xlcomm